package com.lidx.back.statistics.rest.material;

import com.lidx.back.statistics.entity.MaterialRecord;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by chen on 2017/2/17.
 */
public class MaterialRecordPool {

    protected static final Logger logger = LoggerFactory.getLogger(MaterialRecordPool.class);

    private int size;
    private int maxIdel;
    private static ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = null;

    public static BlockingQueue<MaterialRecord> materialRecords;

    public MaterialRecordPool(int size,int maxIdel) {
        materialRecords = new LinkedBlockingQueue<MaterialRecord>();
        this.size = size;
        this.maxIdel = maxIdel;
        /*for (int i = 0; i <size ; i++) {
            materialRecords.offer(new MaterialRecord());
        }*/
        scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(5);
        ClearIdleMaterialRecordsTask task = new ClearIdleMaterialRecordsTask(maxIdel);
        scheduledThreadPoolExecutor.scheduleWithFixedDelay(task,120,120, TimeUnit.SECONDS);

    }

    public static MaterialRecord borrowObject(){
        if(null != materialRecords && materialRecords.size()>0){
            MaterialRecord mr = materialRecords.poll();
            if(mr == null){
                return new MaterialRecord();
            }
            return mr;
        }
        return new MaterialRecord();
    }

    public static void returnObject(MaterialRecord mr){
        mr.setVersionNum(null);
        mr.setVersionType(null);
        mr.setAction(null);
        mr.setChannel(null);
        mr.setDeviceId(null);
        mr.setOnline(null);
        mr.setId(null);
        mr.setRecordTime(null);
        mr.setUuid(null);
        materialRecords.offer(mr);
    }

    public static int getMaterialRecordsSize(){
        return materialRecords.size();
    }

    class ClearIdleMaterialRecordsTask implements Runnable{

        private int maxIdel;

        public ClearIdleMaterialRecordsTask(int maxIdel) {
            this.maxIdel = maxIdel;
        }

        @Override
        public void run() {
            int materialRecordsSize = getMaterialRecordsSize();
            logger.debug("begin clear materialrecords，materialrecords size:{}",materialRecordsSize);
            while (materialRecordsSize > this.maxIdel){
                materialRecords.poll();
            }
        }
    }

}
